package com.example.textview;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.textview.util.TcpHelper;
import com.example.textview.util.ToastUtil;

import java.io.IOException;
import java.security.InvalidParameterException;
import java.util.List;

public class TcpActivity extends AppCompatActivity {
    public EditText editText;
    public TextView textView_send;
    public TextView textView_receive;

    Handler handler;


    private TextView positionTextView;
    private LocationManager locationManager;
    private String provider;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tcp);
        handler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:

                        Bundle bundle = msg.getData();
                        String str = bundle.get("msg").toString();
                        textView_receive.setText(textView_receive.getText().toString() + str + "\n");
                        Log.d("hex",str);
                        break;
                }
            }
        };
        editText = findViewById(R.id.send_editText);
        textView_send = findViewById(R.id.send_textView);
        textView_receive = findViewById(R.id.receive_textView);
        textView_send.setMovementMethod(ScrollingMovementMethod.getInstance());
        textView_receive.setMovementMethod(ScrollingMovementMethod.getInstance());


        TcpHelper.sharedCenter().setDisconnectedCallback(new TcpHelper.OnServerDisconnectedCallbackBlock() {
            @Override
            public void callback(IOException e) {

                ToastUtil.showMsg(TcpActivity.this, "断开连接");
            }
        });

        TcpHelper.sharedCenter().setConnectedCallback(new TcpHelper.OnServerConnectedCallbackBlock() {
            @Override
            public void callback() {

                ToastUtil.showMsg(TcpActivity.this, "连接成功");
            }
        });

        TcpHelper.sharedCenter().setReceivedCallback(new TcpHelper.OnReceiveCallbackBlock() {
            @Override
            public void callback(String receicedMessage) {


                Message message = new Message();
                Bundle bundle = new Bundle();
                bundle.putString("msg", receicedMessage);
                message.setData(bundle);
                message.what = 1;
                handler.sendMessage(message);

            }

            @Override
            public void callback(String receicedMessage, String adr) {

            }
        });

        locationIntin();
    }


    public void sendMessage(View view) {
        String msg = editText.getText().toString();
        textView_send.setText(textView_send.getText().toString() + msg + "\n");
        TcpHelper.sharedCenter().send(msg.getBytes());
    }


    private static int toByte(char c) {
        if (c >= '0' && c <= '9')
            return (c - '0');
        if (c >= 'A' && c <= 'F')
            return (c - 'A' + 10);
        if (c >= 'a' && c <= 'f')
            return (c - 'a' + 10);

        throw new InvalidParameterException("Invalid hex char '" + c + "'");
    }

    public static byte[] hexStringToByteArray(String hexString) {
        int length = hexString.length();
        byte[] buffer = new byte[length / 2];

        for (int i = 0; i < length; i += 2) {
            buffer[i / 2] = (byte) ((toByte(hexString.charAt(i)) << 4) | toByte(hexString
                    .charAt(i + 1)));
        }

        return buffer;
    }



    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }



    public String writeBool(String M, String Status)
    {
        M=M.toUpperCase();
        String ID="02FF0000";

        String index=M.substring(1);
        String strHex = Integer.toHexString(Integer.parseInt(index));
        strHex= strHex.toUpperCase();
        StringBuilder sb = new StringBuilder(strHex);//构造一个StringBuilder对象
        for(int i=sb.length();i<8;i++)
        {
            sb.insert(0,"0");
        }
        strHex= sb.toString();

        Log.d("hex",strHex);
        sb= new StringBuilder();//构造一个StringBuilder对象
        for(int k=0;k<4;k++)
        {
           // ID+=strHex.substring(k*2,2) ;
            sb.insert(0,strHex.substring(k*2,k*2+2));
        }
        strHex= sb.toString();
        //Log.d("hex",strHex);

        if(M.contains("M"))
        {
            ID=ID+strHex+"204D"+"0100";
        }
        else if(M.contains("Y"))
        {
            ID=ID+strHex+"2059"+"0100";

        }


        sb= new StringBuilder(Status);//构造一个StringBuilder对象

        for(int i=Status.length();i<2;i++)
        {

            sb.insert(1,"0");
        }

        ID=ID+sb.toString();

        return ID;

    }

    public void send_1(View view) {

        byte[] bytes = hexStringToByteArray("02FF0000000000002059010010");
        TcpHelper.sharedCenter().send(bytes);

//        bytes = hexStringToByteArray("02FF0000010000002059010010");
//        TcpHelper.sharedCenter().send(bytes);

//        writeBool("Y0","1");
//        writeBool("M200","1");

//        bytes = hexStringToByteArray("01FF0A000000000020591000");
//        TcpHelper.sharedCenter().send(bytes);


//        bytes = hexStringToByteArray("00FF0A000000000020590100");
//        TcpHelper.sharedCenter().send(bytes);
//        bytes = hexStringToByteArray("00FF0A000000000020590200");
//        TcpHelper.sharedCenter().send(bytes);
//        bytes = hexStringToByteArray("00FF0A000000000020590300");
//        TcpHelper.sharedCenter().send(bytes);

        bytes = hexStringToByteArray("01FF0A005A02000020440200");
        TcpHelper.sharedCenter().send(bytes);



        bytes = hexStringToByteArray("03FF000058020000204401005802");
        TcpHelper.sharedCenter().send(bytes);



    }


    public void send_2(View view) {

        byte[] bytes = hexStringToByteArray("02FF0000000000002059010000");
        TcpHelper.sharedCenter().send(bytes);



    }


    public void connect(View view) {
        ToastUtil.showMsg(TcpActivity.this, "connect");
        TcpHelper.sharedCenter().connect("192.168.8.32", 5551);


    }

    public void disconnect(View view) {
        TcpHelper.sharedCenter().disconnect();
    }

    public void clear1(View view) {
        textView_send.setText("");
    }

    public void clear2(View view) {
        textView_receive.setText("");
    }


    void locationIntin() {
        positionTextView = (TextView) findViewById(R.id.position_text_view);
        locationManager = (LocationManager) getSystemService(Context.
                LOCATION_SERVICE);
        List<String> providerList = locationManager.getProviders(true);
        if (providerList.contains(LocationManager.GPS_PROVIDER)) {
            provider = LocationManager.GPS_PROVIDER;
        } else if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {
            provider = LocationManager.NETWORK_PROVIDER;
        } else {
            Toast.makeText(this, "No location provider to use",
                    Toast.LENGTH_SHORT).show();
            Log.d("LOG","退出1");
            return;
        }

        Log.d("LOG","1");
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            Log.d("LOG","退出");
            return;
        }
        Log.d("LOG","2");
        Location location = locationManager.getLastKnownLocation(provider);

        if (location != null) {
            showLocation(location);
            Log.d("LOG","3");
        }
        locationManager.requestLocationUpdates(provider, 5000, 1,
                locationListener);

        Log.d("LOG","4");
    }


    LocationListener locationListener = new LocationListener() {
        @Override
        public void onStatusChanged(String provider, int status, Bundle
                extras) {
        }
        @Override
        public void onProviderEnabled(String provider) {
        }
        @Override
        public void onProviderDisabled(String provider) {
        }
        @Override
        public void onLocationChanged(Location location) {
// 更新当前设备的位置信息
            showLocation(location);
        }
    };

    protected void onDestroy() {
        super.onDestroy();
        if (locationManager != null) {
// 关闭程序时将监听器移除
            locationManager.removeUpdates(locationListener);
        }
    }

    private void showLocation(Location location) {
        String currentPosition = "latitude is " + location.getLatitude() + "\n"
                + "longitude is " + location.getLongitude();
        positionTextView.setText(currentPosition);
    }








}